import 'package:flutter/cupertino.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:svgaplayer_flutter/parser.dart';
import 'package:svgaplayer_flutter/player.dart';

///自定义SVGA缓存动画
class MagicSvga extends StatefulWidget {
  const MagicSvga({
    super.key,
    required this.url,
    this.width,
    this.height,
  });

  final String url;
  final double? width;
  final double? height;

  @override
  State<MagicSvga> createState() => _MagicSvgaState();
}

class _MagicSvgaState<T> extends State<MagicSvga>
    with SingleTickerProviderStateMixin {
  late SVGAAnimationController animationController;

  @override
  void initState() {
    animationController = SVGAAnimationController(vsync: this);
    loadAnimation();
    super.initState();
  }

  @override
  void didUpdateWidget(covariant MagicSvga oldWidget) {
    loadAnimation();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: widget.width,
      height: widget.height,
      child: SVGAImage(animationController),
    );
  }

  void loadAnimation() async {
    var file = await DefaultCacheManager().getSingleFile(widget.url);
    final videoItem =
        await SVGAParser.shared.decodeFromBuffer(file.readAsBytesSync());
    animationController.videoItem = videoItem;
    animationController
        .repeat() // Try to use .forward() .reverse()
        .whenComplete(() => this.animationController.videoItem = null);
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}
